package com.lss.myapplication.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.room.Database;

import com.lss.myapplication.MainActivity;
import com.lss.myapplication.R;
import com.lss.myapplication.db.City;
import com.lss.myapplication.db.County;
import com.lss.myapplication.db.Province;
import com.lss.myapplication.db.database.AppDatabase;
import com.lss.myapplication.util.HttpUtil;
import com.lss.myapplication.util.Utility;

import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {

    private static final String TAG = "ChooseAreaFragment";
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    // 列表
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    // 当前选中的级别
    private int currentLevel;
    // 选中的
    private Province selectedProvince;
    private City selectedCity;
    private County selectedCounty;
    private Button backBtn;
    private TextView titleText;
    private ListView listView;

    private ArrayAdapter<String> adapter;
    private ArrayList<String> dataList = new ArrayList<>();
    private ProgressDialog progressDialog;
    private AppDatabase db;

    // 数据库
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        db = AppDatabase.getInstance(requireContext());
    }

    // 基本完成初始化操作
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area, container, false);
        backBtn = (Button) view.findViewById(R.id.back_button);
        titleText = (TextView) view.findViewById(R.id.title_text);
        listView = (ListView) view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (currentLevel == LEVEL_PROVINCE) {
                selectedProvince = provinceList.get(position);
                queryCities();
            } else if (currentLevel == LEVEL_CITY) {
                selectedCity = cityList.get(position);
                queryCounties();
            }
        });
        backBtn.setOnClickListener(v -> {
            if (currentLevel == LEVEL_CITY) {
                queryCounties();
            } else if (currentLevel == LEVEL_PROVINCE) {
                queryCities();
            }
        });
        queryProvinces();
    }

    private void queryCounties() {
        countyList = db.countyDao().getCountiesByCityId(selectedCity.getId());
        if (!countyList.isEmpty()) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
            titleText.setText(selectedCity.getCityName());
            backBtn.setVisibility(View.VISIBLE);
            if (countyList.isEmpty()) {
                queryFromServer(selectedCity.getCityCode(), "county");
            }
        }
        if (countyList.isEmpty()) {
            int provinceCode = selectedProvince.getId();
            int cityCode = Integer.parseInt(selectedCity.getCityCode());
            String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }

    // 查询所有的县，优先从数据库查询，如果没有查询到再去服务器上查询。
    private void queryCities() {
        cityList = db.cityDao().getCitiesByProvinceId(selectedProvince.getId());
        if (!cityList.isEmpty()) {
            dataList.clear();
            for (City city : cityList) {
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
        } else {
            int provinceCode = selectedProvince.getId();
            String address = "http://guolin.tech/api/china/" + provinceCode;
            queryFromServer(address, "city");
        }
        listView.setSelection(0);
        currentLevel = LEVEL_CITY;
        titleText.setText(selectedProvince.getProvinceName());
        backBtn.setVisibility(View.VISIBLE);
    }

    private void queryProvinces() {
        titleText.setText("中国");
        backBtn.setVisibility(View.GONE);
        // 使用 Room 异步查询
        new Thread(() -> {
            provinceList = db.provinceDao().getAllProvinces();
            // 切换到主线程更新UI
            requireActivity().runOnUiThread(() -> {
                if (provinceList != null && !provinceList.isEmpty()) {
                    dataList.clear();
                    for (Province province : provinceList) {
                        dataList.add(province.getProvinceName());
                    }
                    adapter.notifyDataSetChanged();
                    listView.setSelection(0);
                    currentLevel = LEVEL_PROVINCE;
                } else {
                    queryFromServer("http://guolin.tech/api/china", "province");
                }
            });
        }).start();
    }

    private void queryFromServer(String address, String city) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                assert response.body() != null;
                Log.i(TAG, "onResponse: ");
                String responseText = response.body().string();
                Log.i(TAG, "onResponse: " + responseText);
                boolean result = false;
                if ("province".equals(city)) {
                    try {
                        result = Utility.handleProvinceResponse(responseText, requireContext());
                        if (result) {
                            requireActivity().runOnUiThread(() -> queryProvinces());
                            closeProgressDialog();
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }
                if ("city".equals(city)) {
                    result = Utility.handleCityResponse(responseText, selectedProvince.getId(), requireContext());
                    if (result) {
                        requireActivity().runOnUiThread(() -> queryCities());
                        closeProgressDialog();
                    }
                }
                if ("county".equals(city)) {
                    result = Utility.handleCountyResponse(responseText, selectedCity.getId(), requireContext());
                    if (result) {
                        getActivity().runOnUiThread(() -> queryCounties());
                        closeProgressDialog();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace(); // 打印堆栈跟踪
                Log.e(TAG, "网络请求失败: " + e.getMessage());
                getActivity().runOnUiThread(() -> {
                    closeProgressDialog();
                    Toast.makeText(getContext(), "加载失败111", Toast.LENGTH_SHORT).show();
                });

            }

            private void closeProgressDialog() {
                if (progressDialog != null) {
                    requireActivity().runOnUiThread(() -> progressDialog.dismiss());
                }

            }
        });
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    // 查询省份数据


}
